<script setup lang="ts">
import RoomStatus from './components/room-status.vue'
import RoomAction from './components/room-action.vue'
import RoomMessage from './components/room-message.vue'
// 建立连接，同时判断是否连接成功，离开页面：关闭连接
import io from 'socket.io-client'
import { onMounted } from 'vue'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { onBeforeUnmount } from 'vue'
import type { Socket } from 'socket.io-client'
import type { TSocket, TRoomItem } from '@/types/room'
import { ref } from 'vue'
import { patientConsultOrderDetail } from '@/api/room'
import type { patientConsultOrderDetailApi } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import { nextTick } from 'vue'
import dayjs from 'dayjs'
import { showFailToast } from 'vant'
/*
订单状态:
  1:定义api
  2:导入与调用
  3：存储与渲染
  4：通过socket它状态发生改变时它会通知我们（有一个消息类型针对状态改变）
  5：只要发生改变重新请求
*/
const userStore = useUserStore()
const route = useRoute()
let socket: Socket
const list = ref<TRoomItem[]>([])
const message = ref()
onMounted(() => {
  socket = io(import.meta.env.VITE_APP_URL, {
    auth: {
      token: `Bearer ${userStore.userInfo?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  socket.on('connect', () => {
    console.log('连接成功')
  })
  socket.on('disconnect', () => {
    console.log('关闭连接成功')
  })

  // 接收默认消息
  socket.on('chatMsgList', async (data: TSocket) => {
    console.log(data)
    const arr: TRoomItem[] = []
    data.data.forEach(item => {
      const timeItem = {
        createTime: item.createTime,
        id: item.createTime,
        msgType: 31,
        msg: {
          content: item.createTime
        },
        orderId: item.orderId
      }
      arr.push(timeItem)
      arr.push(...item.items)
    })
    // 累加
    list.value.unshift(...arr)
    loading.value = false
    // 修改下一页请求条件
    time = list.value[0].createTime!
    if (data.data.length === 0) {
      showFailToast('没有更多数据了')
    }

    console.log(list.value)
    if (isFirst) {
      // 让滚动条到最底部
      await nextTick()
      window.scrollTo(0, message.value.scrollHeight)
      isFirst = false
    }
  })

  // 接收消息
  socket.on('receiveChatMsg', async (data: TRoomItem) => {
    list.value.push(data)
    console.log('接收消息', list.value)

    // 让滚动条到最底部
    await nextTick()
    window.scrollTo(0, message.value.scrollHeight)
  })

  // 监听订单状态变化
  socket.on('statusChange', () => {
    getOrderInfo()
  })
})

// 订单状态处理
const orderInfo = ref<patientConsultOrderDetailApi>()
const getOrderInfo = async () => {
  const res = await patientConsultOrderDetail(route.query.orderId as string)
  orderInfo.value = res.data
  console.log('订单状态返回值', res)
}
getOrderInfo()

// 发送文字消息
const sendTxt = (txt: string) => {
  socket.emit('sendChatMsg', {
    from: userStore.userInfo?.id,
    to: orderInfo.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: txt
    }
  })

  console.log('sendTxt')
}

// 发送图片消息
const sendImg = (picture: { id: string; url: string }) => {
  socket.emit('sendChatMsg', {
    from: userStore.userInfo?.id,
    to: orderInfo.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: picture
    }
  })
}

// 下拉加载历史
const loading = ref(false)
let time = dayjs().format('YYYY-MM-DD HH:mm:ss')
let isFirst = true
const onRefresh = () => {
  // 下拉刷新方法触发
  socket.emit('getChatMsgList', 20, time, route.query.orderId)
}

onBeforeUnmount(() => {
  socket.close()
})
</script>

<template>
  <div class="room-page" ref="message">
    <cp-nav-bar title="问诊室" />

    <!-- 状态栏 -->
    <RoomStatus v-if="orderInfo" :orderInfo="orderInfo"></RoomStatus>
    <!-- 聊天内容 -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <RoomMessage v-if="orderInfo" :list="list" :orderInfo="orderInfo"></RoomMessage>
    </van-pull-refresh>
    <!-- 操作栏 -->
    <RoomAction
      @sendTxt="sendTxt"
      @sendImg="sendImg"
      :disabled="orderInfo?.status === OrderType.ConsultChat"
    ></RoomAction>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
